/**
 * Created by lock
 * Date: 2021-06-18
 * Time: 15:19
 */
package connect

import (
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"gochat/config"
	"net/http"
)

// 初始化 websocket
func (c *Connect) InitWebsocket() error {
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		c.serveWs(DefaultServer, w, r)
	})
	err := http.ListenAndServe(config.Conf.Connect.ConnectWebsocket.Bind, nil)
	return err
}

func (c *Connect) serveWs(server *Server, w http.ResponseWriter, r *http.Request) {

	// Upgrader
	//用于升级http请求, 把http请求升级为websocket
	//设置读多少字节，写多少字节
	var upGrader = websocket.Upgrader{
		ReadBufferSize:  server.Options.ReadBufferSize,
		WriteBufferSize: server.Options.WriteBufferSize,
	}
	// 解决跨域
	upGrader.CheckOrigin = func(r *http.Request) bool { return true }

	// 完成ws协议握手操作
	conn, err := upGrader.Upgrade(w, r, nil)

	if err != nil {
		zap.L().Error("serverWs err:%s",zap.Error(err))
		return
	}

	var ch *Channel
	// 默认广播大小eq 512
	ch = NewChannel(server.Options.BroadcastSize)
	ch.conn = conn
	//将数据发送到 websocket conn
	go server.writePump(ch)
	// 从 websocket 连接获取数据
	go server.readPump(ch)
}
